﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using JobDescOnline.Presentation.Models;
using eq.CoreBase.View;
using eq.CoreBase.Control;

namespace JobDescOnline.Presentation.Controllers
{
    public class JobDescriptionController : Controller
    {
        //
        // GET: /JobDescription/

        public JobDescDBEntities1 db = new JobDescDBEntities1();

        public ActionResult Index()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            dynamic model = null;
            int total = 0;

            model = JobDescriptions.RetrieveByFilterAndPage(page, pagesize, sort, direction);
            total = JobDescriptions.RetrieveByFilter();

            ViewData["Dir"] = direction.ToLower() == "asc" ? "desc" : "asc";

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/JobDescription/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();
            return View(model);
        }

        public ActionResult AjaxTable()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            string sort = !string.IsNullOrEmpty(Request.QueryString["sort"]) ? Request.QueryString["sort"] : "ID";
            string direction = !string.IsNullOrEmpty(Request.QueryString["direction"]) ? Request.QueryString["direction"] : "ASC";

            dynamic model = null;
            int total = 0;

            if (filters.Count > 0)
            {
                model = JobDescriptions.RetrieveByFilterAndPage(filters, page, pagesize, sort, direction);
                total = JobDescriptions.RetrieveByFilter(filters);
            }
            else
            {
                model = JobDescriptions.RetrieveByFilterAndPage(page, pagesize, sort, direction);
                total = JobDescriptions.RetrieveByFilter();
            }

            return View(model);
        }

        public ActionResult AjaxPaging()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            int total = 0;

            if (filters.Count > 0)
            {
                total = JobDescriptions.RetrieveByFilter(filters);
            }
            else
            {
                total = JobDescriptions.RetrieveByFilter();
            }

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/JobDescription/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();

            return View();
        }

        //
        // GET: /JobDescription/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /JobDescription/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /JobDescription/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                JobDescription jobdescription = db.JobDescriptions.CreateObject();
                if (ModelState.IsValid)
                {
                    jobdescription.Rowstatus = Convert.ToBoolean(collection["Rowstatus"]);
                    jobdescription.DepartmentID = Convert.ToInt32(collection["DepartmentID"]);
                    jobdescription.JobTitleID = Convert.ToInt32(collection["JobTitleID"]);
                    jobdescription.ReportToJobTitleID = Convert.ToInt32(collection["ReportToJobTitleID"]);
                    jobdescription.Location = collection["Location"];
                    jobdescription.JobPurpose = collection["JobPurpose"];
                    jobdescription.CreatedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    jobdescription.CreatedOn = DateTime.Now;

                    db.JobDescriptions.AddObject(jobdescription);
                    db.SaveChanges();
                }

                return RedirectToAction("Edit/" + jobdescription.ID.ToString());
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /JobDescription/Edit/5
 
        public ActionResult Edit(int id)
        {
            JobDescription jobdescription = db.JobDescriptions.Single(d => d.ID == id);
            IEnumerable<JobDescResponsibility> jobdescresponsibility = db.JobDescResponsibilities.Where(d => d.JobDescriptionID == id);
            IEnumerable<JobDescRelationShip> jobdescrelationshipinternal = db.JobDescRelationShips.Where(d => d.JobDescriptionID == id && d.TypeRelation == "Internal");
            IEnumerable<JobDescRelationShip> jobdescrelationshipexternal = db.JobDescRelationShips.Where(d => d.JobDescriptionID == id && d.TypeRelation == "External");

            List<JobDescResponsibilityModel> jobdescresponsibilitymodel = new List<JobDescResponsibilityModel>();
            JobDescResponsibilityModel model;
            foreach (JobDescResponsibility obj in jobdescresponsibility)
            {
                var item = from p in db.PerformanceIndicators
                           select new PerformanceIndicatorModel
                           {
                               ID = p.ID,
                               Rowstatus = p.Rowstatus,
                               JobDescResponsibilityID = p.JobDescResponsibilityID,
                               PI = p.PI,
                               CreatedBy = p.CreatedBy,
                               CreatedOn = p.CreatedOn,
                               LastModifiedBy = p.LastModifiedBy,
                               LastModifiedOn = p.LastModifiedOn
                           };
                item = item.Where(p => p.JobDescResponsibilityID == obj.ID);

                model = new JobDescResponsibilityModel();
                model.ID = obj.ID;
                model.Rowstatus = obj.Rowstatus;
                model.JobDescriptionID = obj.JobDescriptionID;
                model.MainTask = obj.MainTask;
                model.Activities = obj.Activities;
                model.CreatedBy = obj.CreatedBy;
                model.CreatedOn = obj.CreatedOn;
                model.LastModifiedBy = obj.LastModifiedBy;
                model.LastModifiedOn = obj.LastModifiedOn;
                model.PI = item.ToList();

                jobdescresponsibilitymodel.Add(model);
            }

            JobDescriptionModel jobdescriptionmodel = new JobDescriptionModel
            {
                JobDescription = jobdescription,
                JobDescResponsibilityModel = jobdescresponsibilitymodel,
                JobDescRelationShipInternal = jobdescrelationshipinternal,
                JobDescRelationShipExternal = jobdescrelationshipexternal
            };

            ViewData["ComboJobTitle"] = JobTitles.JobTitleCombo(jobdescription.DepartmentID);
            ViewData["ID"] = jobdescription.ID.ToString();
            return View("Edit", jobdescriptionmodel);
        }

        //
        // POST: /JobDescription/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    JobDescription jobdescription = db.JobDescriptions.First(d => d.ID == id);
                    jobdescription.Rowstatus = true;
                    jobdescription.DepartmentID = Convert.ToInt32(collection["JobDescription.DepartmentID"]);
                    jobdescription.JobTitleID = Convert.ToInt32(collection["JobDescription.JobTitleID"]);
                    jobdescription.ReportToJobTitleID = Convert.ToInt32(collection["JobDescription.ReportToJobTitleID"]);
                    jobdescription.Location = collection["JobDescription.Location"];
                    jobdescription.JobPurpose = collection["JobDescription.JobPurpose"];
                    jobdescription.Capex = collection["JobDescription.Capex"];
                    jobdescription.Opex = collection["JobDescription.Opex"];
                    jobdescription.DirectSubordinates = collection["JobDescription.DirectSubordinates"];
                    jobdescription.IndirectSubordinates = collection["JobDescription.IndirectSubordinates"];
                    jobdescription.LastModifiedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    jobdescription.LastModifiedOn = DateTime.Now;

                    db.JobDescriptions.ApplyCurrentValues(jobdescription);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /JobDescription/Delete/5
 
        public ActionResult Delete(int id)
        {
            JobDescription jobdescription = db.JobDescriptions.Single(d => d.ID == id);
            db.JobDescriptions.DeleteObject(jobdescription);

            db.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
